const fs = require("fs"); // 系统模块 无需安装
const path = require("path"); // 系统模块 无需安装
const compressing = require("compressing"); // 需要安装 npm install compressing
const { addLog } = require("../utils");
const { basePath, pathType } = require("../config");
const MD5 = require("crypto");
module.exports = {
  //解压zip文件
  unzip(unzipPath, type,sdkDir,bool=true) {
    let typePath =
      type == "Android" ? pathType + "baseAndroidSDK" : pathType + "baseIosSDK";
    let fileName =
      unzipPath.split(pathType)[unzipPath.split(pathType).length - 1];
    // 对比版本号
    let oldVersion = fs.readFileSync(
      basePath + typePath + pathType + "_sdkVersion",
      "utf-8"
    );
    if (
      oldVersion == fileName &&
      fs.readdirSync(basePath + typePath).filter(item=>item != '.DS_Store').length > 1
    ) {
      addLog(`${typePath}版本号一致，不需要更新`);
      console.log(`${typePath}版本号一致，不需要更新`);
      return;
    }
    console.log("删除旧skd文件夹", basePath + typePath);
    addLog(`删除旧sdk文件夹${basePath + typePath}`);
    // 获取basePath + typePath 下面的所有文件夹执行删除
    fs.readdirSync(basePath + typePath).forEach((item) => {
      let filePath = path.resolve(__dirname, basePath + typePath, item);
      if (fs.statSync(filePath).isDirectory()) {
        fs.rmSync(filePath, { recursive: true, force: true });
      }
    });
    fs.writeFileSync(basePath + typePath + pathType + "_sdkVersion", fileName);

    if (type != "Android") {
      typePath += pathType+fileName.replace(".zip", "")
    }
    addLog(`解压出来的内容放在${basePath + typePath}文件夹下面`);
    console.log(`解压出来的内容放在${basePath + typePath}文件夹下面`);
    compressing.zip
      .uncompress(unzipPath, basePath + typePath)
      .then(() => {
        addLog(`${typePath}更新成功`);
        console.log(`${typePath}更新成功`);
        addLog(`创建打包sdk local.properties 文件`);
        fs.writeFile(path.resolve(__dirname, basePath + typePath,fileName.replace(".zip", ""),'HBuilder-Integrate-AS', "local.properties"),`sdk.dir=${sdkDir}`,function(err){
          if(err){
            console.log(err)
            addLog(`创建打包sdk local.properties 文件失败`);
          }else{
            addLog(`创建打包sdk local.properties 文件成功`);
          }
        })
        // 修改gradle-wrapper.properties 文件最后一行 distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip 改成 distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-6.5-bin.zip
        fs.readFile(path.resolve(__dirname, basePath + typePath,fileName.replace(".zip", ""),'HBuilder-Integrate-AS', "gradle/wrapper/gradle-wrapper.properties"),'utf-8',function(err,data){
          if(err){
            console.log(err)
            addLog(`修改gradle-wrapper.properties 文件失败`);
          }else{
            let newData = data.replace('https\\://services.gradle.org/distributions','https\\://mirrors.cloud.tencent.com/gradle')
            fs.writeFile(path.resolve(__dirname, basePath + typePath,fileName.replace(".zip", ""),'HBuilder-Integrate-AS', "gradle/wrapper/gradle-wrapper.properties"),newData,function(err){
              if(err){
                console.log(err)
                addLog(`修改gradle-wrapper.properties 文件失败`);
              }else{
                addLog(`修改gradle-wrapper.properties 文件成功`);
              }
            })
          }
        })
        
        // 删除压缩包
        bool && fs.unlinkSync(unzipPath);
      })
      .catch((err) => {
        console.log(err, "err");
        addLog(`${typePath}sdk更新失败`);
      });
  },
  // 复制文件 path:要复制的文件 basePath:复制到哪个文件夹下面
  copySdk(path, basePath) {
    return new Promise((resolve, reject) => {
      fs.copyFile(path, basePath, (err) => {
        if (err) {
          console.log(err, "copyFile err");
          reject(err);
        } else {
          resolve();
        }
      });
    });
  },
  // this.整合切片文件
  async mergeFile(type, md5,fileName,sdkDir) {
    // 切片目录 /temp/${type}
    const dir = path.resolve(__dirname, "../../temp/" + type); //文件名称 0-99
    // 创建一个空的文件
    const filePath = path.resolve(__dirname, "../../temp/" + type, fileName);
    const newFile = fs.createWriteStream(filePath);
    addLog(`开始整合文件${filePath}请等待`);
    // 读取切片文件
    for(let i = 0;i<100;i++){
      let fileDir = path.resolve(__dirname, "../../temp/" + type, i+'');
      let fileData = fs.readFileSync(fileDir);
      await this.writeStream(newFile, fileData,fileDir,i);
    }
    addLog(`整合文件${filePath}完成，提示一次`);
    addLog(`整合文件${filePath}完成，提示两次`);
    addLog(`整合文件${filePath}完成，提示三次`);
    // 关闭文件流
    newFile.end();
    let mewMd5 = '66666666666'
    if(type == "Android"){
      // 获取文件md5值
      let fileBuffer = fs.readFileSync(filePath);
      mewMd5 = MD5.createHash("md5").update(fileBuffer).digest('hex');
    }
    console.log(mewMd5, md5, "mewMd5, md5");
    if (mewMd5 == md5) {
      // 解压文件
      this.unzip(filePath, type,sdkDir);
    }else{
      addLog('sdk文件不完整')
    }
  },

  // 轮询写入文件流传入arr写入一个文件
  writeStream(newFile, fileData,fileDir,index) {
    return new Promise((resolve, reject) => {
      newFile.write(fileData, () => {
        fs.unlinkSync(fileDir);
        resolve()
      });
    });
  }
};
